//
//  AppDelegate.swift
//  MoodDiary
//
//  Created by MoodDiary on 2020/11/24.
//

import UIKit
import UserNotifications
import BUAdSDK
import SwiftyJSON
import AppTrackingTransparency
import AdSupport
import SVProgressHUD
import BackgroundTasks


// 顶部和底部safeArea
func topSafeAreaHeight() -> CGFloat
{
    if #available(iOS 11.0, *)
    {
        return CGFloat(UIApplication.shared.keyWindow?.safeAreaInsets.top ?? 0)
    }
    else
    {
        return 20.0
    }
}

let adWidth = UIScreen.main.bounds.width
let adHeight = UIScreen.main.bounds.width / 9.0 * 16.0

let backgroundTaskID = "com.moodDiary2021.sync.iCloud"

@main
class AppDelegate: UIResponder, UIApplicationDelegate
{
    var window: UIWindow?
    let splashAdView = BUSplashAdView(slotID: "887428229", frame: CGRect(x: 0, y: 100, width: adWidth, height: adHeight))
    var timeStamp = NSDate().timeIntervalSince1970
    let codeView = CodeView(frame: CGRect(x: 0, y: 0, width: screen_width, height: screen_height))
    
    let effect = UIVisualEffectView()//用于隐私的模糊效果
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool
    {
        UMConfigure.initWithAppkey("5fe1b1881283d52b40b1f692", channel: "App Store")
        
        BUAdSDKManager.setAppID("5138561")
        BUAdSDKManager.setLoglevel(.error)
        BUAdSDKManager.setCoppa(0)
        
//        UIApplication.shared.beginReceivingRemoteControlEvents()
        
        if #available(iOS 14, *)
        {
            ATTrackingManager.requestTrackingAuthorization(completionHandler: { status in
                // Tracking authorization completed. Start loading ads here.
                
                if status == .authorized
                {
                    let idfa = ASIdentifierManager.shared().advertisingIdentifier
                    print("IDFA: " + idfa.uuidString)
                    BUAdSDKManager.setCustomIDFA(idfa.uuidString)
                }
                else
                {
                    print("Failed to get IDFA")
                }
                
            })
        }
        
        // 默认广告加载时间30
        if UserDefaults.standard.object(forKey: "adTime") == nil
        {
            UserDefaults.standard.setValue(30, forKey: "adTime")
        }
        
        if UserDefaults.standard.object(forKey: "payTime") == nil
        {
            UserDefaults.standard.setValue(timeStamp, forKey: "payTime")
            UserDefaults.standard.setValue(0, forKey: "payStatus")
            UserDefaults.standard.synchronize()
        }
        
        // 监听网络状态，顺便加载广告配置
        NetworkManager.shared.startNetworkReachabilityObserver()



        
        UNUserNotificationCenter.current().delegate = self
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { (granted, error) in
            if granted {
                // 注册成功
            } else {
                // 注册失败
                print(error)
            }
        }
        
        window?.rootViewController = BaseTabBarController()
        window?.makeKeyAndVisible()
        
        let codeString = UserDefaults.standard.object(forKey: "codeString") as? String
        
        if codeString != nil
        {
            self.showCodeView()
        }
        
        
        // 初始化广告
        initAd()
        
        // 显示广告
        showAd()
        
        DispatchQueue.main.async { [weak self] in
            
        }
        
        //隐私效果
        let blur = UIBlurEffect(style: .regular)
        effect.effect = blur
        effect.frame = UIScreen.main.bounds
        
        return true
    }
    
    func applicationDidEnterBackground(_ application: UIApplication)
    {
        
        print("applicationDidEnterBackground")
        // 记录时间戳
        timeStamp = NSDate().timeIntervalSince1970
        codeView.removeFromSuperview()
    }
    
    func applicationWillEnterForeground(_ application: UIApplication)
    {
        print("applicationWillEnterForeground")
       
        let codeString = UserDefaults.standard.object(forKey: "codeString") as? String
       
        if codeString != nil
        {
            showCodeView(codeType: .input, isInit: false)
        }
        
        // 退出30秒后才显示广告
        if NSDate().timeIntervalSince1970 - timeStamp >= Double(UserDefaults.standard.integer(forKey: "adTime"))
        {
            showAd()
        }
    }
    
    func applicationWillResignActive(_ application: UIApplication) {

        codeView.endEditing(true)
        NotificationCenter.default.post(name: Notification.Name("endEditNotifition"), object: nil)
        let codeString = UserDefaults.standard.object(forKey: "codeString") as? String
       
        if codeString != nil
        {
            if effect.superview == nil{
                UIApplication.shared.keyWindow?.rootViewController?.view.addSubview(effect)
                let viewVC = UIApplication.shared.keyWindow?.rootViewController?.presentedViewController
                if viewVC != nil{
                    
                    viewVC?.dismiss(animated: true, completion: nil)
                }
            }
        }
    }
    
    func applicationDidBecomeActive(_ application: UIApplication) {

        let codeString = UserDefaults.standard.object(forKey: "codeString") as? String
        
        if codeString != nil{
            
            self.showCodeView()
        }
        
        if effect.superview != nil{
            effect.removeFromSuperview()
        }
    }
    
    func showCodeView(codeType: CodeVCType = .input, isInit: Bool = true)
    {
//        fromVC.presentedViewController?.dismiss(animated: false, completion: nil)
        
        codeView.removeFromSuperview()
        codeView.resetCodeView()
        codeView.codeType = codeType
        codeView.delegate = self
        
        // 初始化默认不显示键盘
        if isInit
        {
            codeView.showKeyboard = false
        }
        else
        {
            // 退出30秒后才显示广告
            if NSDate().timeIntervalSince1970 - timeStamp >= Double(UserDefaults.standard.integer(forKey: "adTime"))
            {
                codeView.showKeyboard = false
            }
            else
            {
                codeView.showKeyboard = true
            }
        }
        
        
        
//        alertVC.modalTransitionStyle = .crossDissolve
//        alertVC.modalPresentationStyle = .overCurrentContext
//        fromVC.present(alertC, animated: true, completion: nil)
        
        window?.rootViewController?.view.addSubview(codeView)
    }
    
    // 显示广告方法
    func initAd()
    {
        splashAdView.tolerateTimeout = 3.5
        splashAdView.delegate = self
//        splashAdView.needSplashZoomOutAd = false
        
        //
        let loginImageView = UIImageView(image: UIImage(named: "启动图"))
        loginImageView.contentMode = .scaleAspectFit
        
        // 刘海屏
        if (topSafeAreaHeight() > 20.0)
        {
            loginImageView.frame = CGRect(x: 0, y: Double(-topSafeAreaHeight()), width: screen_width, height: screen_height)
        }
        else
        {
            loginImageView.frame = CGRect(x: 0, y: 0, width: screen_width, height: screen_height)
        }
        
        splashAdView.insertSubview(loginImageView, at: 0)
    }
    
    func showAd()
    {
        splashAdView.loadAdData()
        splashAdView.backgroundColor = .white
        
        // 刘海屏
        if (topSafeAreaHeight() > 20.0)
        {
            splashAdView.frame = CGRect(x: 0, y: topSafeAreaHeight(), width: adWidth, height: UIScreen.main.bounds.height - topSafeAreaHeight())
        }
        else
        {
            splashAdView.frame = CGRect(x: 0, y: 0, width: adWidth, height: UIScreen.main.bounds.height)
        }
        
        window?.rootViewController?.view.addSubview(splashAdView)
        splashAdView.rootViewController = window?.rootViewController
    }
}

extension AppDelegate: BUSplashAdDelegate
{
    func splashAdDidLoad(_ splashAd: BUSplashAdView)
    {
        print("SDK渲染开屏广告加载成功回调")
        
        // 友盟拉去成功事件
        MobClick.event("jrtt_pullsucceed")
    }
    
    func splashAd(_ splashAd: BUSplashAdView, didFailWithError error: Error?)
    {
        print("返回的错误码(error)表示广告加载失败的原因，所有错误码详情请见链接Link")
        splashAd.removeFromSuperview()
        
        // 友盟超时事件
        if (error != nil)
        {
            print("splashAd:didFailWithErrorError:\(String(describing: error))")
            MobClick.event("jrtt_timeout")
        }
    }
    
    func splashAdWillVisible(_ splashAd: BUSplashAdView)
    {
        print("SDK渲染开屏广告即将展示")
        MobClick.event("jrtt_show")
    }
    
    func splashAdDidClick(_ splashAd: BUSplashAdView)
    {
        print("SDK渲染开屏广告点击回调")
        MobClick.event("jrtt_click")
    }
    
    func splashAdDidClose(_ splashAd: BUSplashAdView)
    {
        print("SDK渲染开屏广告关闭回调，当用户点击广告时会直接触发此回调，建议在此回调方法中直接进行广告对象的移除操作")
        splashAd.removeFromSuperview()
    }
    
    func splashAdWillClose(_ splashAd: BUSplashAdView)
    {
        print("SDK渲染开屏广告即将关闭回调")
        splashAd.removeFromSuperview()
    }
    
    func splashAdDidCloseOtherController(_ splashAd: BUSplashAdView, interactionType: BUInteractionType)
    {
        print("此回调在广告跳转到其他控制器时，该控制器被关闭时调用。interactionType：此参数可区分是打开的appstore/网页/视频广告详情页面")
    }
    
    func splashAdDidClickSkip(_ splashAd: BUSplashAdView)
    {
        print("用户点击跳过按钮时会触发此回调，可在此回调方法中处理用户点击跳转后的相关逻辑")
        MobClick.event("jrtt_skip")
    }
    
    func splashAdCountdown(toZero splashAd: BUSplashAdView)
    {
        print("倒计时为0时会触发此回调，如果客户端使用了此回调方法，建议在此回调方法中进行广告的移除操作")
        splashAd.removeFromSuperview()
    }
}

extension AppDelegate: UNUserNotificationCenterDelegate
{
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
    {
        print("通知1")
        completionHandler([.alert, .sound])
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)
    {
        print("通知2")
        completionHandler()
    }
}

extension AppDelegate: CodeViewDeleagate
{
    func codeViewClose()
    {
        
    }
    
    func codeViewUnlock()
    {
        print("解锁")
    }
}

